package com.quanyan.riding.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.riding.constans.Constans;
import com.quanyan.riding.entity.db.TbRunRideLevel;
import com.quanyan.riding.entity.db.TbUser;
import com.quanyan.riding.entity.db.TbUserExample;
import com.quanyan.riding.entity.vo.req.ReqRidingRecord;
import com.quanyan.riding.entity.vo.req.UserInfo;
import com.quanyan.riding.entity.vo.resp.RespRidingFirstPage;
import com.quanyan.riding.entity.vo.resp.RespRidingRecordMonth;
import com.quanyan.riding.entity.vo.resp.RespRidingSideUserInfo;
import com.quanyan.riding.mapper.MyTbRidingRecordMapper;
import com.quanyan.riding.mapper.TbUserMapper;
import com.quanyan.riding.service.RidingPublicService;
import com.quanyan.riding.service.RidingSingleService;
import com.quanyan.riding.service.RidingUserService;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xian-guo
 * @email 498152332@qq.com
 * @date 2016/8/29.
 * 用户处理类
 */
@Service("ridingUserServiceImpl")
public class RidingUserServiceImpl implements RidingUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(RidingUserServiceImpl.class);
    /**
     * 用户表
     */
    @Autowired
    private TbUserMapper tbUserMapper;

    /**
     * 公共服务
     */
    @Autowired
    private RidingPublicService runRidingPublicService;

    /**
     * 用户骑行服务
     */
    @Autowired
    private RidingSingleService ridingSingleService;

    /**
     * 自定义
     */
    @Autowired
    private MyTbRidingRecordMapper myTbRidingRecordMapper;

    /**
     * 用户登录首页面
     * @param userInfo
     * @return
     */
    @Override
    public APIResponse<RespRidingFirstPage> isUserLogin(UserInfo userInfo) {
        //构建返回对象
        RespRidingFirstPage respRidingFirstPage=new RespRidingFirstPage();
        //判断该用户是否存在,不存在插入该用户，否则跟新用户基本信息
        TbUserExample tbUserExample=new TbUserExample();
        tbUserExample.createCriteria().andUserIdEqualTo(userInfo.getUserId()).andUserTypeEqualTo(Constans.RIDINGTYPE);
        List<TbUser> tbUserList=tbUserMapper.selectByExample(tbUserExample);
        if(tbUserList.size()==0){//该用户第一次登录
            try {
                TbUser tbUser=new TbUser();
                tbUser.setUserLevel(Constans.IS_FIRST_LOGIN_LEVEL);//首次登录为1级
                BeanUtils.copyProperties(tbUser,userInfo);
                int insertUser=tbUserMapper.insertSelective(tbUser);
                LOGGER.info("用户首次登录记录用户信息------------------>"+insertUser);
                //查询首次登录用户等级信息
                TbRunRideLevel tbRunRideLevel=runRidingPublicService.getOneRunRideLevel(Constans.RIDINGTYPE, Constans.IS_FIRST_LOGIN_LEVEL);
                //给返回对象赋值
                BeanUtils.copyProperties(respRidingFirstPage,tbUser);
                BeanUtils.copyProperties(respRidingFirstPage,tbRunRideLevel);
                //设置总里程，总均速，总骑行时间为0
                respRidingFirstPage.setUserMileage(0.0);
                respRidingFirstPage.setRidingTime(new BigDecimal(0));
                return APIResponse.returnSuccess(respRidingFirstPage);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        //该用户登录过,跟新用户信息
        TbUser tbUser=tbUserList.get(0);
        try {
            BeanUtils.copyProperties(tbUser,userInfo);
            int updateRidingUser=tbUserMapper.updateByExampleSelective(tbUser,tbUserExample);
            LOGGER.info("--------用户登录跟新用户信息----------->>>>>>>>>>"+updateRidingUser);
            TbRunRideLevel tbRunRideLevel=runRidingPublicService.getOneRunRideLevel(Constans.RIDINGTYPE, tbUser.getUserLevel());
            BeanUtils.copyProperties(respRidingFirstPage,tbUser);
            BeanUtils.copyProperties(respRidingFirstPage,tbRunRideLevel);
            //获取用户骑行总里程和总时间
            List<Map<String,Object>> resultList=myTbRidingRecordMapper.getRidingUserMileage(userInfo.getUserId());
            if (resultList.size()==0){//用户登录过，但没有骑行记录
                respRidingFirstPage.setRidingTime(new BigDecimal(0));
                respRidingFirstPage.setUserMileage(0.0);
                return APIResponse.returnSuccess(respRidingFirstPage);
            }
            Map<String,Object> resultMap=resultList.get(0);
            double mileage= (double) resultMap.get("mileage");
            BigDecimal ridingTime= (BigDecimal) resultMap.get("riding_time");
            respRidingFirstPage.setUserMileage(mileage);
            respRidingFirstPage.setRidingTime(ridingTime);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return APIResponse.returnSuccess(respRidingFirstPage);
    }

    /**
     * 侧边栏获取用户等级信息
     * @param userId
     * @return
     */
    @Override
    public APIResponse<RespRidingSideUserInfo> getSideUserLevelInfo(String userId) {
        TbUserExample tbUserExample=new TbUserExample();
        tbUserExample.createCriteria().andUserIdEqualTo(userId).andUserTypeEqualTo(Constans.RIDINGTYPE);
        TbUser tbRidingUser=tbUserMapper.selectByExample(tbUserExample).get(0);
        RespRidingSideUserInfo respRidingSideUserInfo=new RespRidingSideUserInfo();
        //获取骑行总里程
        Map<String,Object> result=myTbRidingRecordMapper.getRidingUserMileage(userId).get(0);
        respRidingSideUserInfo.setUserMileage((Double) result.get("mileage"));
        respRidingSideUserInfo.setUserLevel(tbRidingUser.getUserLevel());
        //查询用户等级昵称
        TbRunRideLevel tbRunRideLevel=runRidingPublicService.getOneRunRideLevel(Constans.RIDINGTYPE,tbRidingUser.getUserLevel());
        respRidingSideUserInfo.setLevelName(tbRunRideLevel.getLevelName());
        //查询等级集合
        respRidingSideUserInfo.setTbRunRideLevels(runRidingPublicService.getRunRideLevel(Constans.RIDINGTYPE));
        return APIResponse.returnSuccess(respRidingSideUserInfo);
    }

    /**
     * 路书上用户个人主页
     * @param reqRidingRecord
     * @return
     */
    @Override
    public APIResponse<Map<String, Object>> getRidingPathUserDetailMsg(ReqRidingRecord reqRidingRecord) {
        //获取用户信息
        TbUserExample tbUserExample=new TbUserExample();
        tbUserExample.createCriteria().andUserIdEqualTo(reqRidingRecord.getUserId()).andUserTypeEqualTo(Constans.RIDINGTYPE);
        TbUser tbRidingUser=tbUserMapper.selectByExample(tbUserExample).get(0);
        //获取用户等级信息
        TbRunRideLevel tbRunRideLevel=runRidingPublicService.getOneRunRideLevel(Constans.RIDINGTYPE, tbRidingUser.getUserLevel());
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("levelName",tbRunRideLevel.getLevelName());
        paramMap.put("photoUrl",tbRidingUser.getPhotoUrl());
        paramMap.put("gender",tbRidingUser.getGender());
        paramMap.put("userNick",tbRidingUser.getUserNick());
        paramMap.put("userLevel",tbRidingUser.getUserLevel());
        paramMap.put("userId",tbRidingUser.getUserId());//查看生涯记录详情需要
        //获取骑行生涯记录
        APIResponse<PageObj<List<RespRidingRecordMonth>>> apiResponse=ridingSingleService.getMonthRidingRecord(reqRidingRecord);
        paramMap.put("pageObj",apiResponse.getData());
        return APIResponse.returnSuccess(paramMap);
    }
}
